/*
 * @Author: tomystery
 * @Date:   2017-09-13 14:42:55
 * @Last Modified by:   tomystery
 * @Last Modified time: 2017-09-14 15:36:23
 */

'use strict';

require('./index.css');

require('page/common/header/index.js');
var nav=require('page/common/nav/index.js');
var _mm = require('util/mm.js');
var _cart = require('service/cart-service.js');
var templateIndex = require('./index.string');

var page = {
    data: {

    },
    init: function() {
        this.onLoad();
        this.bindEvent();


    },
    onLoad: function() {
        this.loadCart();


    },
    bindEvent: function() {
        var _this = this;
        //1.商品的选择 /取消
        $(document).on('click', '.cart-select', function() {
            var $this = $(this);
            //获取productId
            var productId = $this.parents('.cart-table').data('product-id');
            //选中
            if ($this.is(':checked')) {
                _cart.selectProduct(productId, function(res) {
                    _this.renderCart(res);
                }, function(errMsg) {
                    _this.showCartError();
                })
            }
            //取消选中
            else {
                _cart.unselectProduct(productId, function(res) {
                    _this.renderCart(res);
                }, function(errMsg) {
                    _this.showCartError();
                })
            }

        });

        //2.全选的选择 /取消
        $(document).on('click', '.cart-select-all', function() {
            var $this = $(this);
            //全选
            if ($this.is(':checked')) {
                _cart.selectAllProduct(function(res) {
                    _this.renderCart(res);
                }, function(errMsg) {
                    _this.showCartError();
                })
            }
            //取消全选
            else {
                _cart.unselectAllProduct(function(res) {
                    _this.renderCart(res);
                }, function(errMsg) {
                    _this.showCartError();
                })
            }

        });
        //3.点击加减
        $(document).on('click', '.count-btn', function() {
            var $this = $(this);
            var productId = $this.parents('.cart-table').data('product-id');
            var type = $(this).data('opera-type');
            var currentCount =$this.siblings('.count-input').val();
            var newCount;

            var stock = $('.count-input').data('max');
            if (type === 'minus') {
                newCount = currentCount > 1 ? currentCount - 1 : 1
                if (currentCount <= 1) {
                    _mm.errorTips('对不起，商品不能再少了')
                } else {
                    newCount = currentCount - 1
                }
            } else if (type === 'plus') {
                if (currentCount >= stock) {
                    _mm.errorTips('对不起，商品不能再多了')

                } else {
                    newCount = parseInt(currentCount) + 1;
                }
            }


            //更新购物车数量
            _cart.updateProduct({
                productId: productId,
                count: newCount
            }, function(res) { //成功的话就渲染
                _this.renderCart(res);
            }, function(errMsg) {
                _this.showCartError();
            });
        });


        //4.删除单个商品
        $(document).on('click', '.cart-delete', function() {
            if (window.confirm('确认要删除该商品？')) {
                var productId = $(this).parents('.cart-table')
                    .data('product-id');
                _this.deleteCartProduct(productId);
            }
        });

        //5.删除选中项
         $(document).on('click', '.cart-delete-seleced', function() {
         	 if (window.confirm('确认要删除选中的商品？')) {
               var arrProductIds=[];
             var   $selectedItems=$('.cart-select:checked');
               console.log($selectedItems);
               for(var i=0;i<$selectedItems.length;i++){
               	arrProductIds.push($($selectedItems[i]).parents('.cart-table').data('product-id'));
               }

             if(arrProductIds.length){
             	_this.deleteCartProduct(arrProductIds.join(','));
             }else{
             	_mm.errorTips('您还没有选中商品！')
             }
            }
         });

         //6.提交购物车
         $(document).on('click','.submit-btn',function(){
         	//如果有价钱则可以提交
         	if(_this.data.cartInfo && _this.data.cartInfo.cartTotalPrice>0){
         		window.location.href = './order-confirm.html';
         	}else{
         		_mm.errorTips('请选中结算商品！')
         	}
         })




    },
    loadCart: function() {
        var _this = this;


        //获取购物车列表
        _cart.getCartList(function(res) {
            console.log(res);
            _this.renderCart(res);
        }, function(errMsg) {
            $('.cart-wrap').html('<p class="err-tip">哪里不对了，刷新下试试吧。</p>')
        })
    },
    //渲染购物车
    renderCart: function(data) {
        this.filter(data);
        //缓存购物车信息
        this.data.cartInfo = data;
        //生成html
        var cartHtml = _mm.renderHtml(templateIndex, data);
        $('.cart-wrap').html(cartHtml);
         //更新导航条中的购物车数量
           nav.loadCartCount();
    },
    //数据匹配
    filter: function(data) {
        data.notEmpty = !!data.cartProductVoList.length;
    },
    //购物车选中出错
    showCartError: function() {
        $('.cart-wrap').html('<p class="err-tip">哪里不对了，刷新下试试吧。</p>');
    },
    //删除指定商品，支持批量,productId用逗号分隔
    deleteCartProduct: function(productIds) {
        var _this = this;
        _cart.deleteProduct(productIds, function(res) {
            _this.renderCart(res);
        }, function(errMsg) {
            _this.showCartError();
        })

    }






};
page.init();